package com.fs.console.base.vo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 下拉树
 */
@Data
public class TreeData {
    private String id;

    private String name;

    private Boolean open = true;

    private Boolean checked = false;

    private String treeId = "id" ;

    private String treePid = "pId";

    private Object o;

    private List<TreeData> children;

    public TreeData(String treeId,String treePid,Object o,String id,String name){
        this.id = id;
        this.name = name;
        this.treeId = treeId;
        this.treePid = treePid;
        this.o = o;
    }

    private List<TreeData> getTreeData(List rows, String treeId, String treePid,String name){
        List<TreeData> treeList = new ArrayList<>();
        String json = JSON.toJSONString(rows);
        JSONArray array = JSON.parseArray(json);
        String treeIdValue = null ,treePidValue = null,nameValue = null;
        for(int i=0,len=array.size();i<len;i++){
            JSONObject item = array.getJSONObject(i);
            treeIdValue = item.getString(treeId);
            nameValue = item.getString(name);
            treePidValue = item.getString(treePid)==null? "" : item.getString(treePid);
            TreeData tree = new TreeData(treeIdValue, treePidValue, item,treeIdValue,nameValue);
            treeList.add(tree);
        }
        List<TreeData> nodeList = new ArrayList<TreeData>();
        for(TreeData node1 : treeList){
            boolean mark = false;
            for(TreeData node2 : treeList){
                if(node1.getTreePid()!=null && node1.getTreePid().equals(node2.getTreeId())){
                    mark = true;
                    if(node2.getChildren() == null) {
                        node2.setChildren(new ArrayList<TreeData>());
                    }
                    node2.getChildren().add(node1);
                    break;
                }
            }
            if(!mark){
                nodeList.add(node1);
            }
        }
        return nodeList;
    }
}
